<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="user-scalable=no, initial-scale=1.0" />
    <title></title>
    <script src="./TOOL/vue_2.6.14.js"></script>
    <script src="./TOOL/vue-router_3.5.2.js"></script>
    <script src="./TOOL/axios.js"></script>
    <link rel="stylesheet" href="./css/element-ui_2.15.3.css" />
    <script src="./TOOL/element-ui_2.15.3.js"></script>
    <script src="./format.js"></script>
    <script src="./pages.js"></script>
    <script>
      //用axios来向Cgi发送XHR来读写PLC
      axios.defaults.headers.post["Content-Type"] =
        "application/x-www-form-urlencoded";

      function SendToCgi(addr, param) {
        return axios({
          method: "post",
          url: "/cgi/" + addr,
          data: param,
        });
      }

      function Cgi_get(pageObj, param, ioAddr) {
        if (ioAddr) {
          param = "NUM=" + ioAddr.length + param;
        }
        // ioAddr && console.log(ioAddr);
        // console.log(param);
        SendToCgi("RdDevRnd.cgi", param)
          .then(function (response) {
            // console.log(response.data);
            //此处省略返回码判断逻辑

            let data = response.data.DATA;
            if (data.length > 0) {
              ioAddr.forEach((item, index) => {
                pageObj.plc[item].value = data[index];
              });
            }
          })
          .catch((err) => console.error(err, "内部网络错误"));
      }

      //根据设备屏幕大小来设置页面大小
      let EL_ROW_STYLE = (function () {
        let style = document.createElement("style");
        style.appendChild(document.createTextNode(""));
        document.head.appendChild(style);
        return style;
      })();

      function resizeView() {
        let devHeight = window.screen.height,
          devWidth = window.screen.width;
        if (devHeight > devWidth) {
          [devHeight, devWidth] = [devWidth, devHeight];
        }
        if (devHeight > 768) {
          devHeight = 768;
        }
        if (devWidth > 1024) {
          devWidth = 1024;
        }
        while (EL_ROW_STYLE.sheet.rules.length > 0) {
          EL_ROW_STYLE.sheet.removeRule(0);
        }
        let rowNum = document.querySelectorAll(".el-row").length;
        EL_ROW_STYLE.sheet.insertRule(
          `.grid-content {height:${Math.floor(
            (devHeight - rowNum * 4 - 18) / rowNum
          )}px}`,
          0
        );
        EL_ROW_STYLE.sheet.insertRule(`#app {width:${devWidth - 17}px`, 0);
      }
    </script>
    <script src=""></script>
    <style>
      * {
        padding: 0;
        margin: 0;
        box-sizing: border-box;
      }
      #app {
        margin: 6px;
      }
      hr {
        margin-top: 20px;
      }
      .grid-content {
        margin: 2px 0;
        border-radius: 4px;
        background: #e5e9f2;
      }
      .WRtest {
        margin: 50px 20px;
        width: 760px;
      }
      .WRtest .el-button--primary {
        margin-left: 50px;
      }
    </style>
  </head>
  <body>
    <div id="app">
      <router-view></router-view>
    </div>
    <script>
      const MainTimerCycle = 5; //页面数值自动刷新时间
      function refreshPageVal(pageObj) {
        //查询字符串 NUM=3&DEV1=D10&TYP1=W&DEV2=D11&TYP2=D&DEV3=M0&TYP3=B ,NUM<10
        let param = "",
          addrArray = [];
        num = 0;
        for (var addr in pageObj.plc) {
          if (Object.hasOwnProperty.call(pageObj.plc, addr)) {
            addrArray.push(addr);
            num++;
            param += `&DEV${num}=${addr}&TYP${num}=${pageObj.plc[addr].type}`;
            //读超过9个会报错，三菱怕不是零时工写的接口
            if (num > 8) {
              let ioAddr = addrArray.slice(0);
              Cgi_get(pageObj, param, ioAddr);

              addrArray = [];
              num = 0;
              param = "";
            }
          }
        }
        if (num > 0) {
          Cgi_get(pageObj, param, addrArray);
        }
      }
      const Grid = {
        template: PAGES.grid,
        mounted: function () {
          this.$nextTick(function () {
            resizeView();
          });
        },
      };
      const Rule = {
        template: PAGES.rule,
        data() {
          let validateAddr = (rule, value, callback) => {
            if (value === "") {
              callback(new Error("地址不能为空"));
            } else if (RegExp(/^[X|Y|B|W][0-9a-fA-F]+$/gi).test(value)) {
              callback();
            } else if (RegExp(/^S[B|W][0-9a-fA-F]+$/gi).test(value)) {
              callback();
            } else if (RegExp(/^[M|F|S|L|D|Z|R]\d{1,6}$/gi).test(value)) {
              callback();
            } else if (RegExp(/^S?T[N|S|C]\d{1,6}$/gi).test(value)) {
              callback();
            } else if (RegExp(/^L?C[N|S|C]\d{1,6}$/gi).test(value)) {
              callback();
            } else if (RegExp(/^S[D|M]\d{1,6}$/gi).test(value)) {
              callback();
            } else if (RegExp(/^LZ\d{1,6}$/gi).test(value)) {
              callback();
            } else if (RegExp(/^BL\d{1,6}$/gi).test(value)) {
              callback();
            } else {
              callback(new Error("请输入正确的PLC地址"));
            }
          };
          let validateType = (rule, value, callback) => {
            if (value === "B") {
              callback();
            } else if (value === "W") {
              callback();
            } else if (value === "D") {
              callback();
            } else {
              return callback(new Error("数据类型错误"));
            }
          };
          return {
            textarea: "",
            copyarea: "",
            ruleForm: {
              addr: "",
              type: "",
              val: "",
            },
            rules: {
              addr: [{ validator: validateAddr, trigger: "blur" }],
              type: [{ validator: validateType, trigger: "blur" }],
              val: "",
            },
            options: [
              {
                value: "B",
                label: "  B/bit",
              },
              {
                value: "W",
                label: "  W/16bit",
              },
              {
                value: "D",
                label: "  D/32bit",
              },
            ],
          };
        },
        computed: {
          addrToUpper: {
            get: function () {
              return this.ruleForm.addr;
            },
            set: function (val) {
              this.ruleForm.addr = val.toUpperCase();
            },
          },
        },
        methods: {
          read(formName) {
            let that = this;
            this.$refs[formName].rules.val = "";
            this.$refs[formName].validate((valid) => {
              if (valid) {
                let param = `NUM=1&DEV1=${this.ruleForm.addr}&TYP1=${this.ruleForm.type}`;
                SendToCgi("RdDevRnd.cgi", param)
                  .then(function (response) {
                    let data = response.data;
                    console.log(data);
                    that.textarea = JSON.stringify(data);
                    that.copyarea += param + "  RdDevRnd.cgi\n";
                  })
                  .catch((err) => console.error(err, "内部网络错误"));
              } else {
                alert("提交参数有误");
                return false;
              }
            });
          },
          write(formName) {
            this.$refs[formName].rules.val = [
              {
                validator: (rule, value, callback) => {
                  if (value === "") {
                    return callback(new Error("写入值不能为空"));
                  }
                  callback();
                },
                trigger: "blur",
              },
            ];

            let that = this;
            this.$refs[formName].validate((valid) => {
              if (valid) {
                let param = `NUM=1&DEV1=${this.ruleForm.addr}&TYP1=${this.ruleForm.type}&DATA1=${this.ruleForm.val}`;
                SendToCgi("WrDev.cgi", param)
                  .then(function (response) {
                    let data = response.data;
                    console.log(data);
                    that.textarea = JSON.stringify(data);
                    that.copyarea += param + "  WrDev.cgi\n";
                  })
                  .catch((err) => console.error(err, "内部网络错误"));
              } else {
                alert("提交参数有误");
                return false;
              }
            });
          },
        },
      };
      const Main = {
        data: function () {
          return {
            loopTimer: "",
            plc: {
              X23: { value: "", type: "B" },
              Y2a: { value: "", type: "B" },
              M46: { value: "", type: "B" },
              SM5: { value: "", type: "B" },
              L37: { value: "", type: "B" },
              B0A: { value: "", type: "B" },
              SB2D: { value: "", type: "B" },
              F53: { value: "", type: "B" },
              S34: { value: "", type: "B" },
              TS1: { value: "", type: "B" },
              TC1: { value: "", type: "B" },
              TN1: { value: "", type: "W" },
              STS3: { value: "", type: "B" },
              STC3: { value: "", type: "B" },
              STN3: { value: "", type: "W" },
              CS0: { value: "", type: "B" },
              CC0: { value: "", type: "B" },
              CN0: { value: "", type: "W" },
              LCS1: { value: "", type: "B" },
              LCC1: { value: "", type: "B" },
              LCN1: { value: "", type: "D" },
              R0: { value: "", type: "W" },
              R1: { value: "", type: "W" },
              D0: { value: "", type: "W" },
              D1: { value: "", type: "W" },
              SD0: { value: "", type: "W" },
              SD1: { value: "", type: "W" },
              W0: { value: "", type: "W" },
              W1: { value: "", type: "W" },
              SW0: { value: "", type: "W" },
              SW1: { value: "", type: "W" },
              Z0: { value: "", type: "W" },
              Z1: { value: "", type: "W" },
              LZ1: { value: "", type: "D" },
            },
          };
        },
        template: PAGES.main,
        created: function () {
          refreshPageVal(this);
          if (!this.loopTimer) {
            this.loopTimer = setInterval(() => {
              refreshPageVal(this);
            }, MainTimerCycle * 1000);
          }
        },
        mounted: function () {
          this.$nextTick(function () {
            resizeView();
          });
        },
        beforeDestroy: function () {
          this.loopTimer && clearInterval(this.loopTimer);
        },
      };
      const Device = {
        data: function () {
          return {
            loopTimer: "",
            plc: {
              Xd: { value: "", type: "B" },
              X23: { value: "", type: "B" },
              X4c: { value: "", type: "B" },
              Ye: { value: "", type: "B" },
              Y16: { value: "", type: "B" },
              Y2a: { value: "", type: "B" },
              M14: { value: "", type: "B" },
              M46: { value: "", type: "B" },
              SM5: { value: "", type: "B" },
              SM21: { value: "", type: "B" },
              L37: { value: "", type: "B" },
              L68: { value: "", type: "B" },
              B8: { value: "", type: "B" },
              B0A: { value: "", type: "B" },
              B3B: { value: "", type: "B" },
              SB7: { value: "", type: "B" },
              SB0C: { value: "", type: "B" },
              SB2D: { value: "", type: "B" },
              F9: { value: "", type: "B" },
              F53: { value: "", type: "B" },
              S18: { value: "", type: "B" },
              S34: { value: "", type: "B" },
              TS1: { value: "", type: "B" },
              TC1: { value: "", type: "B" },
              TN1: { value: "", type: "W" },
              STS3: { value: "", type: "B" },
              STC3: { value: "", type: "B" },
              STN3: { value: "", type: "W" },
              CS0: { value: "", type: "B" },
              CC0: { value: "", type: "B" },
              CN0: { value: "", type: "W" },
              LCS1: { value: "", type: "B" },
              LCC1: { value: "", type: "B" },
              LCN1: { value: "", type: "D" },
              R0: { value: "", type: "W" },
              R1: { value: "", type: "W" },
              D0: { value: "", type: "W" },
              D1: { value: "", type: "W" },
              SD0: { value: "", type: "W" },
              SD1: { value: "", type: "W" },
              W0: { value: "", type: "W" },
              W1: { value: "", type: "W" },
              SW0: { value: "", type: "W" },
              SW1: { value: "", type: "W" },
              Z0: { value: "", type: "W" },
              Z1: { value: "", type: "W" },
              LZ1: { value: "", type: "D" },
            },
          };
        },
        template: PAGES.device,
        created: function () {
          refreshPageVal(this);
          if (!this.loopTimer) {
            this.loopTimer = setInterval(() => {
              refreshPageVal(this);
            }, MainTimerCycle * 1000);
          }
        },
        mounted: function () {
          this.$nextTick(function () {
            resizeView();
          });
        },
        beforeDestroy: function () {
          this.loopTimer && clearInterval(this.loopTimer);
        },
      };

      const routes = [
        { path: "/", name: "主页面", component: Main },
        { path: "/device", name: "设备监控页面", component: Device },
        { path: "/grid", name: "分格页面", component: Grid },
        { path: "/rule", name: "读写规则测试", component: Rule },
      ];

      const router = new VueRouter({
        routes,
      });
      router.beforeEach((to, from, next) => {
        document.title = to.name;
        next();
      });

      const app = new Vue({
        el: "#app",
        router,
      });
    </script>
  </body>
</html>
